<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Whack A Mole!</title>
		<link
			href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700"
			rel="stylesheet"
			type="text/css" />
		<link
			rel="stylesheet"
			href="style.css" />
		<link
			rel="icon"
			href="https://fav.farm/🔥" />
	</head>
	<body>
		<h1>Whack-a-mole! <span class="score">0</span></h1>
		<button onClick="startGame()">Start!</button>

		<div class="game">
			<div class="hole hole1">
				<div class="mole"></div>
			</div>
			<div class="hole hole2">
				<div class="mole"></div>
			</div>
			<div class="hole hole3">
				<div class="mole"></div>
			</div>
			<div class="hole hole4">
				<div class="mole"></div>
			</div>
			<div class="hole hole5">
				<div class="mole"></div>
			</div>
			<div class="hole hole6">
				<div class="mole"></div>
			</div>
		</div>

		<script>
			const holes = document.querySelectorAll('.hole');
			const scoreBoard = document.querySelector('.score');
			const moles = document.querySelectorAll('.mole'); //  获取所有地鼠
			let isGameOver = false;
			let lastTimeHole = null;
			let score = 0;
			let duration = 10000;
			let range = 618;

			let randomTime = () => {
				let randomTime = Math.floor(Math.random() * range + 382);
				return randomTime;
			};
			let randomHoles = () => {
				let index = Math.floor(Math.random() * holes.length);
				let currentHole = holes[index];
				if (currentHole === lastTimeHole) {
					return randomHoles();
				} else {
					lastTimeHole = currentHole;
					return currentHole;
				}
			};

			moles.forEach((mole) => {
				mole.addEventListener('click', (e) => {
					if (!e.isTrusted) return;
					score++;
					scoreBoard.textContent = score;
					mole.parentElement.classList.remove('up');
				});
			});

			const startGame = () => {
				isGameOver = false;
				score = 0;
				scoreBoard.textContent = score;
				popUpMole();
				setTimeout(() => {
					isGameOver = true;
				}, duration);
			};
			let popUpMole = () => {
				let time = randomTime();
				let randomHole = randomHoles();
				randomHole.classList.add('up');
				setTimeout(() => {
					randomHole.classList.remove('up');
					if (!isGameOver) popUpMole();
					else return;
				}, time);
			};
		</script>
	</body>
</html>
